package cn.zhz.springdoc.springboot.listen;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import cn.zhz.springdoc.core.dto.ApiPushDto;
import cn.zhz.springdoc.springboot.property.OpenApiProperty;
import cn.zhz.springdoc.springboot.service.IOpenApiParser;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;

import static cn.zhz.springdoc.core.constant.SpringDocConstant.PUSH_API_OK;
import static cn.zhz.springdoc.core.constant.SpringDocConstant.PUSH_API_URL;

/**
 * @author ZHZ
 * @since 2022-11-15
 */
@Slf4j
@RequiredArgsConstructor
public class OpenApiPushApplicationStartupRunner implements ApplicationRunner {

    private final OpenApiProperty openApiProperty;

    private final IOpenApiParser iOpenApiParser;


    @Override
    public void run(ApplicationArguments args) {
        new Thread(() -> {
            ApiPushDto apiPushDto = iOpenApiParser.parser();
            if (apiPushDto == null) {
                return;
            }
            String apiPushJson = JSONUtil.toJsonStr(apiPushDto);
            String result = HttpUtil.post(openApiProperty.getServerUrl() + PUSH_API_URL, apiPushJson);

            if (PUSH_API_OK.equals(result)) {
                log.debug("openApi远程推送成功：apiPushJson: {}", apiPushJson);
                log.info("openApi远程推送成功");
            } else {
                log.error("openApi远程推送失败：{}", result);
            }
        }).start();
    }

}
